package cn.tiansu.eway.common.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;
import org.logicalcobwebs.proxool.ProxoolDataSource;
import org.logicalcobwebs.proxool.configuration.JAXPConfigurator;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 多数据源连接数据库
 * @Title: DBConnection.java
 * @Description: TODO
 * @author: 吴鹏 
 * @date: 2015年9月10日
 * 
 *
 */
public class DBConnection
{
	private final static String driver = "org.logicalcobwebs.proxool.ProxoolDriver";
	private final static String defaultAlias = "xml-test";
	private final static String proxool = "proxool.xml";
	private final static Map<String, ProxoolDataSource> mutilDataBasePool = new ConcurrentHashMap<String, ProxoolDataSource>(
			new HashMap<String, ProxoolDataSource>());

	
	private final static Logger log = Logger.getLogger(DBConnection.class);

	private static DBConnection instance = new DBConnection();

	public static DBConnection getInstance()
	{
		return instance;
	}

	/**
	 * 加载驱动，读取配置文件
	 */
	private DBConnection()
	{
		try
		{
			Class.forName(driver);
			JAXPConfigurator.configure(proxool, false);
			buildProxoolDs(defaultAlias);
		}
		catch (Exception e)
		{
			log.info(e);
		}
	}

	/**
	 * 加载数据源
	 * 
	 * @param alias
	 *            数据库别名
	 * @return
	 */
	private ProxoolDataSource buildProxoolDs(String alias)
	{
		ProxoolDataSource pds = mutilDataBasePool.get(alias);
		if (pds == null)
		{
			pds = new ProxoolDataSource(alias);
			mutilDataBasePool.put(alias, pds);
		}
		return pds;
	}

	/**
	 * 获取数据库模板
	 * 
	 * @return
	 */
	public JdbcTemplate getJdbcTemplate()
	{
		return getJdbcTemplate(defaultAlias);
	}

	/**
	 * 获取数据库模板
	 * 
	 * @return
	 */
	public JdbcTemplate getJdbcTemplate(String alias)
	{
		ProxoolDataSource pds = buildProxoolDs(alias);
		if (pds != null)
		{
			return new JdbcTemplate(pds);
		}
		else
		{
			log.warn("there is no ProxoolDataSource,alias is " + alias);
		}
		return null;
	}
}
